{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c972e2eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "from  sklearn import datasets\n",
    "from sklearn.model_selection import train_test_split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "75df67ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "cancer_data = datasets.load_breast_cancer()\n",
    "water_data = pd.read_csv('./Datas/water.csv', index_col='编号')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "4dc54c52",
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_data = water_data.iloc[:, :-1]\n",
    "raw_target = water_data.iloc[:, -1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "7b67f7d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train,x_test,y_train,y_test = train_test_split(raw_data, raw_target,test_size=0.3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "7fa06a1a",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>色泽</th>\n",
       "      <th>根蒂</th>\n",
       "      <th>敲声</th>\n",
       "      <th>纹理</th>\n",
       "      <th>脐部</th>\n",
       "      <th>触感</th>\n",
       "      <th>好瓜</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>编号</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>青绿</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>乌黑</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>沉闷</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>乌黑</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>青绿</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>沉闷</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>浅白</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>青绿</td>\n",
       "      <td>稍蜷</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>稍凹</td>\n",
       "      <td>软粘</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>乌黑</td>\n",
       "      <td>稍蜷</td>\n",
       "      <td>浊响</td>\n",
       "      <td>稍糊</td>\n",
       "      <td>稍凹</td>\n",
       "      <td>软粘</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>乌黑</td>\n",
       "      <td>稍蜷</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>稍凹</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>乌黑</td>\n",
       "      <td>稍蜷</td>\n",
       "      <td>沉闷</td>\n",
       "      <td>稍糊</td>\n",
       "      <td>稍凹</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>青绿</td>\n",
       "      <td>硬挺</td>\n",
       "      <td>清脆</td>\n",
       "      <td>清晰</td>\n",
       "      <td>平坦</td>\n",
       "      <td>软粘</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>浅白</td>\n",
       "      <td>硬挺</td>\n",
       "      <td>清脆</td>\n",
       "      <td>模糊</td>\n",
       "      <td>平坦</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>浅白</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>模糊</td>\n",
       "      <td>平坦</td>\n",
       "      <td>软粘</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>青绿</td>\n",
       "      <td>稍蜷</td>\n",
       "      <td>浊响</td>\n",
       "      <td>稍糊</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>浅白</td>\n",
       "      <td>稍蜷</td>\n",
       "      <td>沉闷</td>\n",
       "      <td>稍糊</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>乌黑</td>\n",
       "      <td>稍蜷</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>稍凹</td>\n",
       "      <td>软粘</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>浅白</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>模糊</td>\n",
       "      <td>平坦</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>青绿</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>沉闷</td>\n",
       "      <td>稍糊</td>\n",
       "      <td>稍凹</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>否</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    色泽  根蒂  敲声  纹理  脐部  触感 好瓜\n",
       "编号                           \n",
       "1   青绿  蜷缩  浊响  清晰  凹陷  硬滑  是\n",
       "2   乌黑  蜷缩  沉闷  清晰  凹陷  硬滑  是\n",
       "3   乌黑  蜷缩  浊响  清晰  凹陷  硬滑  是\n",
       "4   青绿  蜷缩  沉闷  清晰  凹陷  硬滑  是\n",
       "5   浅白  蜷缩  浊响  清晰  凹陷  硬滑  是\n",
       "6   青绿  稍蜷  浊响  清晰  稍凹  软粘  是\n",
       "7   乌黑  稍蜷  浊响  稍糊  稍凹  软粘  是\n",
       "8   乌黑  稍蜷  浊响  清晰  稍凹  硬滑  是\n",
       "9   乌黑  稍蜷  沉闷  稍糊  稍凹  硬滑  否\n",
       "10  青绿  硬挺  清脆  清晰  平坦  软粘  否\n",
       "11  浅白  硬挺  清脆  模糊  平坦  硬滑  否\n",
       "12  浅白  蜷缩  浊响  模糊  平坦  软粘  否\n",
       "13  青绿  稍蜷  浊响  稍糊  凹陷  硬滑  否\n",
       "14  浅白  稍蜷  沉闷  稍糊  凹陷  硬滑  否\n",
       "15  乌黑  稍蜷  浊响  清晰  稍凹  软粘  否\n",
       "16  浅白  蜷缩  浊响  模糊  平坦  硬滑  否\n",
       "17  青绿  蜷缩  沉闷  稍糊  稍凹  硬滑  否"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "water_data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c01d2a8",
   "metadata": {},
   "source": [
    "# 朴素贝叶斯"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 173,
   "id": "b84a6775",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "class Bayes:\n",
    "    \n",
    "    \n",
    "    def __init__(self, data, target):\n",
    "        \n",
    "        self.dit = ['否','是']\n",
    "        self.data = data\n",
    "        self.target = target\n",
    "        self.n_feature = data.shape[1]\n",
    "        self.n_target = len(np.unique(target))\n",
    "        p_t = len(target[target == '是']) / len(target)\n",
    "        p_f = 1 - p_t\n",
    "        self.p_tar = [p_f, p_t]\n",
    "        self.p_condition = np.zeros((self.n_feature,np.max(data.apply(lambda x: len(np.unique(x)))), self.n_target))\n",
    "        self.calc_condition()\n",
    "        pass\n",
    "    \n",
    "    def calc_condition(self):\n",
    "        # 计算条件概率\n",
    "        \n",
    "        for i in range(self.n_feature):\n",
    "            for j in range(len(pd.unique(self.data.iloc[:, i]))):\n",
    "                for k in range(self.n_target):\n",
    "                    flatten_data = self.data.iloc[:, i].values.flatten()\n",
    "                    unique_featrue = pd.unique(self.data.iloc[:, i])\n",
    "                    len_con = len(self.target[(self.target == self.dit[k]) & (flatten_data == unique_featrue[j])])\n",
    "                    len_all = len(self.target[self.target == self.dit[k]])\n",
    "                    self.p_condition[i][j][k] =  len_con / len_all\n",
    "                                                     \n",
    "    def predict(self, inputs):\n",
    "        # 查概率表\n",
    "        arr = np.array([])\n",
    "        for i in range(len(inputs)):\n",
    "            p_t = self.p_tar[1]\n",
    "            p_f = self.p_tar[0]\n",
    "            for j in range(self.n_feature):\n",
    "                index = np.where(pd.unique(self.data.iloc[:, j]) == inputs.iloc[i, j])[0][0]\n",
    "                p_t *= self.p_condition[j][index][1]\n",
    "                p_f *= self.p_condition[j][index][0]\n",
    "            \n",
    "            res =  self.dit[int(p_t > p_f)]\n",
    "            arr = np.append(arr, res)\n",
    "            \n",
    "        return arr\n",
    "                \n",
    "\n",
    "b = Bayes(raw_data, raw_target)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 175,
   "id": "1e42fc29",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['是', '是', '是', '是', '是', '是', '否', '是', '否', '否', '否', '否', '是',\n",
       "       '否', '是', '否', '否'], dtype='<U32')"
      ]
     },
     "execution_count": 175,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b.predict(raw_data)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
